let currentAudio = null;
let correctAnswer = null;
let errorWords = [];

// 在全局作用域添加布局检查函数
function checkLayout() {
    const container = document.getElementById('quiz-container');
    if (!container) return;
    
    // 动态调整容器高度以适应视口
    const vh = window.innerHeight * 0.01;
    container.style.height = `calc(${vh * 100}px - 60px)`;
    
    // 防止内容溢出
    const answerGrid = document.getElementById('answer-grid');
    if (answerGrid) {
        answerGrid.style.maxHeight = `calc(${vh * 100}px - ${container.offsetTop + 200}px)`;
    }
}

// 页面加载初始化
document.addEventListener('DOMContentLoaded', () => {
    setupEventListeners();
    displayCurrentWord();
    checkLayout();  // 确保布局正确
    document.getElementById('customAlert').style.display = 'none';
});

// 新增事件监听器初始化函数
function setupEventListeners() {
    const nextBtn = document.getElementById('next-btn');
    if (nextBtn) {
        nextBtn.addEventListener('click', () => {
            currentIndex++;
            displayCurrentWord();
        });
    }

    // 弹窗确认按钮事件
    document.getElementById('confirmBtn')?.addEventListener('click', () => {
        document.getElementById('customAlert').style.display = 'none';
    });

    // 弹窗取消按钮事件
    document.getElementById('confirmCancel')?.addEventListener('click', () => {
        document.getElementById('customAlert').style.display = 'none';
    });
}

// 新增UI重置函数
function resetUI() {
    // 重置单词显示
    const wordDisplay = document.getElementById('word-display');
    wordDisplay.textContent = '';
    wordDisplay.style.display = 'none';
    
    // 重置图片显示
    const imageElement = document.getElementById('word-image');
    imageElement.style.display = 'none';
    imageElement.src = '';
    
    // 清空选项按钮
    const grid = document.getElementById('answer-grid');
    while (grid.firstChild) {
        grid.removeChild(grid.firstChild);
    }
    
    // 隐藏下一题按钮
    document.getElementById('next-btn').style.display = 'none';
    
    // 重置反馈状态
    const feedback = document.getElementById('feedback');
    feedback.className = 'feedback';
    feedback.textContent = '';
}

// 新增反馈重置函数
function resetFeedback() {
    const feedback = document.getElementById('feedback');
    feedback.className = 'feedback';
    feedback.textContent = '';
}

// 新增音频播放函数
function playSound(soundUrl) {
    if (currentAudio) {
        currentAudio.pause();
        currentAudio.currentTime = 0;
    }
    currentAudio = new Audio(soundUrl);
    currentAudio.play();
}

// 修改答题处理函数
function handleAnswer(selected, questionType) {
    resetFeedback();

    // 根据题型判断正确性
    let isCorrect = false;
    switch(questionType) {
        case 'imageSelectText':
        case 'chineseSelectText':
        case 'soundSelectText':
            isCorrect = selected === correctAnswer;
            break;
        case 'textSelectImage':
            isCorrect = selected === correctAnswer;
            break;
        default:
            isCorrect = selected === correctAnswer;
            break;
    }

    const feedback = document.getElementById('feedback');

    if (isCorrect) {
        feedback.className = 'feedback correct';
        feedback.textContent = '回答正确';
    } else {
        errorWords.push(words[currentIndex].id);
        feedback.className = 'feedback incorrect';
        feedback.textContent = '回答错误';
    }

    highlightAnswer(selected, isCorrect);
    // 无论对错都显示下一题按钮
    document.getElementById('next-btn').style.display = 'block';
}

// 修改显示当前单词函数
function displayCurrentWord() {
    if (!window.words || window.words.length < 4) {
        showCustomAlert(
           "请至少选择4个单词进行练习",
           () => window.location.href = ctx + 'student/get',
           () => window.location.href = ctx + 'student/get'
       );
        return;
    }
    resetUI();

    if (currentIndex >= window.words.length) {
        // 新增错题处理逻辑
        if (errorWords.length > 0) {
            showCustomAlert(
                "答题已完成，点击确定查看错题列表",
                () => {
                    // 跳转到错题列表
                    window.location.href = ctx + `student/get?errorWords=${errorWords.join(',')}`;
                },
                () => {
                    // 取消则返回首页
                    window.location.href = ctx + 'student/get';
                }
            );
        } else {
            showCustomAlert(
                "恭喜！全部答对！",
                () => window.location.href = ctx + 'student/get',
                () => window.location.href = ctx + 'student/get'
            );
        }
        return;
    }

    const currentWord = window.words[currentIndex];
    // 定义题型枚举
    const questionTypes = [
        'default',          // 原有题型：显示单词+图片，选中文
        'imageSelectText',  // 显示图片，选单词
        'textSelectImage',  // 显示单词，选图片
        'chineseSelectText',// 显示中文，选单词
        'soundSelectText'   // 播放音频，选单词
    ];
    // 随机选择题型
    const currentType = questionTypes[
        Math.floor(Math.random() * questionTypes.length)
    ];

    // 根据题型设置显示内容
    switch(currentType) {
        case 'imageSelectText':
            document.getElementById('word-display').style.display = 'none';
            const imageElement = document.getElementById('word-image');
            imageElement.src = currentWord.image;
            imageElement.style.display = 'block';
            break;
        case 'textSelectImage':
            // 修改：添加词性字段
            document.getElementById('word-display').textContent = 
                `${currentWord.name}（${currentWord.partOfSpeech}）`;
            document.getElementById('word-display').style.display = 'block';
            document.getElementById('word-image').style.display = 'none';
            break;
        case 'chineseSelectText':
            // 修改：添加词性字段
            document.getElementById('word-display').textContent = 
                `${currentWord.meaning}（${currentWord.partOfSpeech}）`;
            document.getElementById('word-display').style.display = 'block';
            document.getElementById('word-image').style.display = 'none';
            break;
        case 'soundSelectText':
            document.getElementById('word-display').innerHTML = 
                `<button class="sound-btn" onclick="playSound('${currentWord.sound}')">🔊 播放音频</button>`;
            document.getElementById('word-display').style.display = 'block';
            document.getElementById('word-image').style.display = 'none';
            break;
        default:
            // 修改：添加词性字段
            document.getElementById('word-display').textContent = 
                `${currentWord.name}（${currentWord.partOfSpeech}）`;
            const imageEl = document.getElementById('word-image');
            if (currentWord.image && currentWord.image.trim() !== '') {
                imageEl.src = currentWord.image;
                imageEl.style.display = 'block';
            } else {
                imageEl.style.display = 'none';
            }
            break;
    }

    // 生成选项
    const options = generateOptions(currentWord, currentType);
    // 创建按钮
    const grid = document.getElementById('answer-grid');
    options.forEach(option => {
        const btn = createAnswerButton(option, currentType);
        grid.appendChild(btn);
    });
    
    // 保存正确答案
    correctAnswer = getCorrectAnswer(currentWord, currentType);
}

// 新增获取正确答案函数
function getCorrectAnswer(word, questionType) {
    switch(questionType) {
        case 'imageSelectText':
        case 'chineseSelectText':
        case 'soundSelectText':
            return word.name;
        case 'textSelectImage':
            return word.image;
        default:
            return word.meaning;
    }
}

// 修改generateOptions函数
function generateOptions(correctWord, questionType) {
    // 获取所有备选单词
    const otherWords = window.words.filter(w => w.id !== correctWord.id);
    
    // 根据题型生成选项
    switch(questionType) {
        case 'imageSelectText': // 图片选单词
        case 'chineseSelectText': // 中文选单词
        case 'soundSelectText': // 音频选单词
            const textOptions = [correctWord.name];
            const randomTexts = shuffleArray(otherWords)
                               .slice(0, 3)
                               .map(w => w.name);
            return shuffleArray([...textOptions, ...randomTexts]);
        case 'textSelectImage': // 单词选图片
            const imageOptions = [correctWord.image];
            const randomImages = shuffleArray(otherWords)
                                 .slice(0, 3)
                                 .map(w => w.image);
            return shuffleArray([...imageOptions, ...randomImages]);
        default: // 原有题型
            const meaningOptions = [correctWord.meaning];
            const randomMeanings = shuffleArray(otherWords)
                                   .slice(0, 3)
                                   .map(w => w.meaning);
            return shuffleArray([...meaningOptions, ...randomMeanings]);
    }
}

// 修改createAnswerButton函数
function createAnswerButton(option, questionType) {
    const btn = document.createElement('button');
    btn.className = 'answer-btn';
    
    // 根据题型设置按钮内容
    switch(questionType) {
        case 'textSelectImage': // 图片选项
            btn.innerHTML = '';
            const img = document.createElement('img');
            img.src = option;
            img.className = 'option-image';
            img.style.width = '100%';
            img.style.height = '100%';
            img.style.objectFit = 'contain';
            btn.appendChild(img);
            break;
        case 'imageSelectText': // 文字选项
        case 'chineseSelectText':
        case 'soundSelectText':
        default:
            btn.textContent = option;
            break;
    }
    
    btn.addEventListener('click', () => handleAnswer(option, questionType));
    return btn;
}

// 新增高亮答案函数
function highlightAnswer(selected, isCorrect) {
    const buttons = document.querySelectorAll('.answer-btn');
    buttons.forEach(button => {
        // 清除现有样式
        button.classList.remove('correct', 'incorrect');
        
        // 获取选项值（文本或图片src）
        let optionValue = '';
        if (button.textContent.trim() !== '') {
            optionValue = button.textContent.trim();
        } else {
            const img = button.querySelector('.option-image');
            if (img) {
                optionValue = img.src.trim();
            }
        }
        
        // 添加正确/错误样式
        if (optionValue === correctAnswer) {
            button.classList.add('correct');
        } else if (!isCorrect && optionValue === selected) {
            button.classList.add('incorrect');
        }
    });
    
    // 禁用所有选项点击
    buttons.forEach(btn => btn.disabled = true);
}

// 新增shuffleArray函数
function shuffleArray(array) {
    if (!array || !Array.isArray(array)) return [];
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
}

// 新增showCustomAlert函数
function showCustomAlert(message, confirmCallback, cancelCallback) {
    const modal = document.getElementById('customAlert');
    const messageEl = modal.querySelector('.modal-message');
    const confirmBtn = document.getElementById('confirmBtn');
    const cancelBtn = document.getElementById('confirmCancel');
    
    if (messageEl) messageEl.textContent = message;
    
    if (confirmBtn && confirmCallback) {
        confirmBtn.onclick = () => {
            // 新增：在跳转前调用updateErrorWords接口
            if (errorWords.length > 0) {
                fetch(ctx + 'student/get/update-error-words', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ errorIds: errorWords })
                }).then(response => {
                    if (response.ok) {
                        modal.style.display = 'none';
                        confirmCallback();
                    }
                }).catch(error => {
                    console.error('更新错题失败:', error);
                    // 即使失败也继续跳转，但提示错误
                    modal.style.display = 'none';
                    confirmCallback();
                });
            } else {
                modal.style.display = 'none';
                confirmCallback();
            }
        };
    }
    
    if (cancelBtn && cancelCallback) {
        cancelBtn.onclick = () => {
            modal.style.display = 'none';
            cancelCallback();
        };
    }
    
    modal.style.display = 'block';
}
